﻿using King.Box.Models.Util;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;

namespace King.Box.AdminWeb.Filter
{
    public class CustomExceptionAttribute : HandleErrorAttribute
    {
        public override void OnException(ExceptionContext filterContext)
        {
            if (filterContext.ExceptionHandled)
                return;

            if (filterContext.RequestContext.HttpContext.Request.IsAjaxRequest())
            {
                var responseData = new ResponseData();
                switch (filterContext.HttpContext.Response.StatusCode)
                {
                    case (int)HttpStatusCode.Unauthorized:
                        responseData = ResponseData.Failtrue(HttpStatusCode.Unauthorized.ToString());
                        break;
                    default:
                        responseData = ResponseData.Failtrue(string.Concat(filterContext.Exception.Message,filterContext.Exception.InnerException?.Message));
                        break;
                }

                filterContext.HttpContext.Response.Clear();
                filterContext.Result = new JsonResult() { Data = responseData };
                filterContext.HttpContext.Response.TrySkipIisCustomErrors = true;
                filterContext.HttpContext.Response.StatusCode = (int)HttpStatusCode.OK;
                goto BaseExcute;
            }

            switch (filterContext.HttpContext.Response.StatusCode)
            {
                case (int)HttpStatusCode.NotFound:
                    filterContext.Result = new RedirectResult("/Home/Error404");
                    break;
                default:
                    filterContext.Result = new RedirectResult("/Home/Error500");
                    break;
            }

            BaseExcute:
                filterContext.ExceptionHandled = true;
                base.OnException(filterContext);
        }
    }
}